package cc.idoone.spring_boot_hello.ehcache;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;

/**
 * 缓存配置
 *
 * @auther hemj
 * @since 2017/9/27
 */
@Configuration
@EnableCaching //标注启动缓存
public class EhcacheConfig {

	/**
	 * ehcache 主要的管理器
	 */
	@Primary
	@Bean
	public CacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean) {
		System.out.println("CacheConfiguration.ehCacheCacheManager()");
		return new EhCacheCacheManager(bean.getObject());
	}

	/**
     * 据 shared 与否的设置, Spring 分别通过CacheManager.create() 或new CacheManager()方式来创建一个ehcache 基地.
     * 也说是说通过这个来设置cache 的基地是这里的Spring独用, 还是跟别的(如hibernate 的Ehcache 共享)
     */
	@Bean
	public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
		System.out.println("CacheConfiguration.ehCacheManagerFactoryBean()");
		EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
		cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
		cacheManagerFactoryBean.setShared(true);
		return cacheManagerFactoryBean;
	}

}
